﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class Habitant : MonoBehaviour {

	// Properties
	//
	//

	public float MoodLevel = 0;

	private float PlateauHeight = 125f;
	private float PlateauWidth = 150f;

	private float RandomNavTime = 15f;
	private float CurrentNavigationTime = 0f;


	public List<AudioClip> SonsHabitants = new List<AudioClip> ();

	public NavMeshAgent navMeshAgent;


	// Methods
	//
	//

	// Use this for initialization
	void Start ()
	{
		float x = Random.Range(-this.PlateauWidth, this.PlateauWidth);
		float y = Random.Range(-this.PlateauHeight, this.PlateauHeight);

		this.navMeshAgent = this.GetComponent<NavMeshAgent>();

		this.GetComponent<NavMeshAgent>().SetDestination(new Vector3(x, 0, y));

		this.StartCoroutine("CoroutineSound");

	}
	
	// Update is called once per frame
	void Update ()
	{
		this.CurrentNavigationTime += Time.deltaTime;

		if(this.CurrentNavigationTime > this.RandomNavTime)
		{
			this.CurrentNavigationTime = 0f;

			float x = Random.Range(-this.PlateauWidth, this.PlateauWidth);
			float y = Random.Range(-this.PlateauHeight, this.PlateauHeight);

			this.GetComponent<NavMeshAgent>().SetDestination(new Vector3(x, 0, y));
		}
	}

	public void UpdateMoodLevel(float mood)
	{
		this.MoodLevel = mood;
		// TODO Change graph if level change

		// Set the speed depending on the mood
		// C'est degeulasse mais j'ai la flemme :3
		float speed = 5f;
		int moodLevel = 3;


		if(this.MoodLevel < -200){
			speed = 2f;
			this.GetComponentInChildren<MeshRenderer>().material.color = new Color(1f,0f,0.3f,0f);
			this.audio.pitch = 0.8f;
		}
		else if(this.MoodLevel < -100){
			speed = 4f;
			this.GetComponentInChildren<MeshRenderer>().material.color = new Color(0.8f,0.2f,0.3f,0f);
			this.audio.pitch = 0.9f;
		}
		else if(this.MoodLevel < 100){
			speed = 5f;
			this.GetComponentInChildren<MeshRenderer>().material.color = new Color(0.6f,0.4f,0.3f,0f);
			this.audio.pitch = 1f;
		}
		else if(this.MoodLevel < 300){
			speed = 6f;
			this.GetComponentInChildren<MeshRenderer>().material.color = new Color(0.3f,0.7f,0.3f,0f);
			this.audio.pitch = 1f;
		}
		else
		{
			speed = 7f;
			this.GetComponentInChildren<MeshRenderer>().material.color = new Color(0.2f,0.78f,0.2f,0f);
			this.audio.pitch = 1.2f;
		}

		this.GetComponent<NavMeshAgent>().speed = speed;

		//



	}


	IEnumerator CoroutineSound(){

		System.Random rng = new System.Random ();

		this.audio.clip = this.SonsHabitants[rng.Next(0, this.SonsHabitants.Count)];
		this.audio.Play();

		yield return new WaitForSeconds((float)rng.NextDouble()*50);

		this.StartCoroutine("CoroutineSound");

	}

}
